<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\MessageActionRequest;
use App\Models\Message;
use App\Models\Group;
use App\Http\Resources\UserResource;

class MessageActionController extends Controller
{
    public function vote(MessageActionRequest $request)
    {

        $message = $request->message;
        $type = $request->type;//agree refuse waiver

        if(!isset($message['unique_slug'])){
            return response()->json(['code'=>1,'msg'=>'该消息是模拟消息，不支持投票','data'=>[]]);
        }
        $modelMessage = Message::where('unique_slug', $message['unique_slug'])->first();

        if(!$modelMessage){
            return response()->json(['code'=>1,'msg'=>'消息错误','data'=>[]]);
        }


        /** 可用redis */
        if(!file_exists(storage_path('app/vote_message_lock.txt'))){
            file_put_contents(storage_path('app/vote_message_lock.txt'),'111');
        }
        $fp = fopen(storage_path('app/vote_message_lock.txt'), 'r');
        if( flock($fp, LOCK_EX | LOCK_NB) ){//非阻塞锁

        }else{
            return response()->json(['code'=>1,'投票人数太多,请稍后再试']);
            fclose($fp);
        }
        /**  可用redis */


        try{

    
            $user = $request->user();
    
            
            if($modelMessage->message_type=='post'){//朋友圈点餐是好友即可
                
                $divideGroup = $user->divideGroups()->whereHasIn('users',function($query)use($modelMessage){
                    $query->where('id',$modelMessage->from_id);
                })->first();

                if(!$divideGroup){//要点赞用户朋友圈，不再自己的好友列表里
                    return response()->json(['code'=>1,'msg'=>'您没有权限！！！','data'=>[]]);

                }
                
            }else{
                $group = Group::findOrFail($modelMessage->to_id);
                if(!$group->users()->where('id',$user->id)->exists()){
                    return response()->json(['code'=>1,'msg'=>'您没有权限！！','data'=>[]]);
                }
            }

    
    
            $data = $modelMessage->data;
    
    
            if(!isset($data['extra']['vote_extra']['vote_user_ids'])){
                $data['extra']['vote_extra']['can_vote_user_ids']=[];//在发送信息的时候，可以记录下当前可以投票的用户
                $data['extra']['vote_extra']['vote_user_ids']=[];
                $data['extra']['vote_extra']['agree_users']=[];
                $data['extra']['vote_extra']['refuse_users']=[];
                $data['extra']['vote_extra']['waiver_users']=[];
            }
    
            // if(!in_array($user->id,$data['extra']['can_vote_user_ids'])){
            //     return response()->json(['code'=>1,'msg'=>'您没有权限！！!','data'=>[]]);
            // }
    
            if(in_array($user->id,$data['extra']['vote_extra']['vote_user_ids'])){//
                switch($type){
                    case 'agree':
                        $actionUsers = collect($data['extra']['vote_extra']['agree_users']);
                        $userId = $user->id;
                        $actionUsers = $actionUsers->filter(function($item)use($userId){
                            return $item['id']!=$userId;
                        });
                        $data['extra']['vote_extra']['agree_users'] = $actionUsers->values()->all();
                        break;
                    case 'refuse':
                        $actionUsers = collect($data['extra']['vote_extra']['refuse_users']);
                        $userId = $user->id;
                        $actionUsers = $actionUsers->filter(function($item)use($userId){
                            return $item['id']!=$userId;
                        });
                        $data['extra']['vote_extra']['refuse_users'] = $actionUsers->values()->all();
                        break;
                    case 'waiver':
                        $actionUsers = collect($data['extra']['vote_extra']['waiver_users']);
                        $userId = $user->id;
                        $actionUsers = $actionUsers->filter(function($item)use($userId){
                            return $item['id']!=$userId;
                        });
                        $data['extra']['vote_extra']['waiver_users'] = $actionUsers->values()->all();
                        break;
                }
                $vote_user_ids = $data['extra']['vote_extra']['vote_user_ids'];

                $key = array_search($user->id,$vote_user_ids);
                array_splice($vote_user_ids, $key, 1);
                $data['extra']['vote_extra']['vote_user_ids'] = $vote_user_ids;
    
                $modelMessage->data = $data;
        
                $modelMessage->save();
            }else{
                switch($type){
                    case 'agree':
                        $data['extra']['vote_extra']['agree_users'][] = new UserResource($user);
                        break;
                    case 'refuse':
                        $data['extra']['vote_extra']['refuse_users'][] = new UserResource($user);
                        break;
                    case 'waiver':
                        $data['extra']['vote_extra']['waiver_users'][] = new UserResource($user);
                        break;
                }
                $data['extra']['vote_extra']['vote_user_ids'][] = $user->id;
    
                $modelMessage->data = $data;
        
                $modelMessage->save();
        
            }
    
           
           
            
            event(new \App\Events\MessageActionVote($modelMessage));
            
            flock($fp, LOCK_UN);
            fclose($fp);
        }catch(\Exception $e){//避免死锁
            flock($fp, LOCK_UN);
            fclose($fp);
            return response()->json(['code'=>1,'msg'=>$e->getFile().'-'.$e->getLine().'-'.$e->getMessage()]);
        }
       


        return response()->json(['code'=>0,'msg'=>'操作成功']);
        

    }
}
